package com.atmilan.quartz.utils.product;

import cn.hutool.core.map.MapUtil;
import cn.hutool.crypto.digest.DigestUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.atmilan.quartz.model.dto.daigo.DaigoBrandResult;
import com.atmilan.quartz.model.dto.daigo.DaigoCateResult;
import com.atmilan.quartz.model.dto.daigo.DaigoProductResDTO;
import com.atmilan.quartz.model.entity.daigo.DaigoBrand;
import com.atmilan.quartz.model.entity.daigo.DaigoCate;
import com.atmilan.quartz.model.entity.efasion.EfasionProductSku;
import com.atmilan.quartz.sync.pull.daigo.mapper.DaigoBrandMapper;
import com.atmilan.quartz.sync.pull.daigo.mapper.DaigoCateMapper;
import com.atmilan.quartz.sync.pull.daigo.service.impl.DaigoBrandServiceImpl;
import com.atmilan.quartz.sync.pull.daigo.service.impl.DaigoCateServiceImpl;
import com.atmilan.quartz.utils.RestTemplateUtil;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.Instant;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ThreadLocalRandom;
import java.util.stream.Collectors;

/**
 * 拉取商品源数据
 */

@Slf4j
@Service
public class DaigoProductUtil {

    @Autowired
    RestTemplateUtil restTemplateUtil;

    @Resource
    DaigoBrandMapper daigoBrandMapper;

    @Resource
    DaigoCateMapper daigoCateMapper;

    @Autowired
    DaigoBrandServiceImpl daigoBrandServiceImpl;

    @Autowired
    DaigoCateServiceImpl daigoCateServiceImpl;

    @Value("${daigo.url}")
    private String daigoUrl;
    @Value("${daigo.appkey}")
    private String daigoAppKey;
    @Value("${daigo.appsecret}")
    private String daigoAppSecret;

    /**
     * 获取daigo商品数据和详情
     * @Description:
     * @author daigb
     * @param @param id 商品barCode
     * @param @return
     * @param @throws Exception
     * @return DaigoProductResDTO
     * @throws
     */
    public DaigoProductResDTO getDaigoProductByBarCode(String barCode) throws Exception {
        DaigoProductResDTO daigoProductResDTO = null;
        try {
            if (StringUtil.isEmpty(barCode) || 4 >= barCode.length()) {
                return null;
            }
            String id = barCode.substring(4, barCode.length());

            // log.info("--------------- 查询daigo远程数据, 商品id: {} ---------------", id);
            String timestamp = String.valueOf(Instant.now().getEpochSecond());
            String random = String.valueOf(ThreadLocalRandom.current().nextInt(1000, 9999));
            String signature = getSignature(timestamp, random);
            Map<String, String> parMap = new HashMap<String, String>();
            parMap.put("appkey", this.daigoAppKey);
            parMap.put("appsecret", this.daigoAppSecret);
            parMap.put("t", timestamp);
            parMap.put("r", random);
            parMap.put("s", signature);
            parMap.put("op", "goods");
            parMap.put("action", "list");
            parMap.put("goods_ids", id);
            String result = restTemplateUtil.getData(this.daigoUrl + "?appkey={appkey}&appsecret={appsecret}&t={t}&r={r}&s={s}&op={op}&action={action}&goods_ids={goods_ids}", parMap);
            // log.info("--------------- daigo远程数据返回结果: {} ---------------", result);

            ObjectMapper mapper = new ObjectMapper();
            daigoProductResDTO = mapper.readValue(result, DaigoProductResDTO.class);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return daigoProductResDTO;
    }


    /**
     * 获取daigo商品列表
     * @Description:
     * @author daigb
     * @param @param pageNow
     * @param @param pageSize
     * @param @return
     * @param @throws Exception
     * @return DaigoProductResDTO
     * @throws
     */
    public DaigoProductResDTO selectDaigoPage(Integer pageNow, Integer pageSize) throws Exception {
        DaigoProductResDTO daigoProductResDTO = null;
        try {
            String timestamp = String.valueOf(Instant.now().getEpochSecond());
            String random = String.valueOf(ThreadLocalRandom.current().nextInt(1000, 9999));
            String signature = getSignature(timestamp, random);
            Map<String, String> parMap = new HashMap<String, String>();
            parMap.put("appkey", this.daigoAppKey);
            parMap.put("appsecret", this.daigoAppSecret);
            parMap.put("t", timestamp);
            parMap.put("r", random);
            parMap.put("s", signature);
            parMap.put("op", "goods");
            parMap.put("action", "list");
            parMap.put("p", pageNow + "");
            parMap.put("n", pageSize + "");
            parMap.put("stock", "1");
            JSONObject obj = new JSONObject();
            obj.putAll(parMap);
            log.info("selectDaigoPage=>请求参数:{}",obj.toJSONString());
            String result = restTemplateUtil.getData(this.daigoUrl + "?appkey={appkey}&appsecret={appsecret}&t={t}&r={r}&s={s}&op={op}&action={action}&p={p}&n={n}&stock={stock}", parMap);
//            log.info("--------------- 查询daigo远程数据, result:{}  ---------------", result);
            ObjectMapper mapper = new ObjectMapper();
            daigoProductResDTO = mapper.readValue(result, DaigoProductResDTO.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return daigoProductResDTO;
    }

    // Daigo商品库存计算
    private Integer getDaigoStockByBarCode(String barCode, String color, String size) {
        int stock = 0;
        try {
            DaigoProductResDTO daigoProductResDTO = getDaigoProductByBarCode(barCode);
            if (null == daigoProductResDTO || StringUtil.isEmpty(color) || StringUtil.isEmpty(size)) {
                log.info("--------------- 查询daigo远程数据, 商品为空: {} 或参数缺失, color:{}, size: {} ---------------", null == daigoProductResDTO, color, size);
                return stock;
            }
            List<DaigoProductResDTO.Product> products = daigoProductResDTO.getProduct();
            if (CollectionUtils.isEmpty(products)) {
                log.info("--------------- 查询daigo远程数据, products为空, barCode:{}  ---------------", barCode);
                return stock;
            }
            List<DaigoProductResDTO.ProductSku> productSkus = products.get(0).getSkus();
            if (CollectionUtils.isEmpty(productSkus)) {
                log.info("--------------- 查询daigo远程数据, productSkus为空, barCode:{}  ---------------", barCode);
                return stock;
            }
            DaigoProductResDTO.ProductSku productSku = productSkus.stream().filter(obj -> obj.getColor().equals(color) && obj.getSize().equals(size)).findFirst().orElse(null);

            return null == productSku ? stock : productSku.getStock();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return stock;
    }

    // 签名
    private String getSignature(String timestamp, String random) {
        String signStr = null;
        try {
            Map<String, String> signMap = MapUtil.newHashMap(4);
            signMap.put("timeStamp", timestamp);
            signMap.put("randomStr", random);
            signMap.put("appkey", this.daigoAppKey);
            signMap.put("appsecret", this.daigoAppSecret);

            List<String> valueList = signMap.entrySet().stream().sorted(Map.Entry.comparingByValue()).map(Map.Entry::getValue).collect(Collectors.toList());
            signStr = String.join("", valueList);
            signStr = DigestUtil.sha1Hex(signStr);
            signStr = DigestUtil.md5Hex(signStr);
            signStr = DigestUtil.md5Hex(signStr);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return signStr.toUpperCase();
    }

    /**
     * 获取daigo商品分类
     * @Description:
     * @author daigb
     * @param @param id 商品barCode
     * @param @return
     * @param @throws Exception
     * @return DaigoProductResDTO
     * @throws
     */
    public void getDaigoCatList() throws Exception {
        DaigoCateResult daigoCatResResult = null;
        try {

            List<DaigoCate> daigoCateEntity = new ArrayList<>();
            daigoCateMapper.deleteAll();

            String timestamp = String.valueOf(Instant.now().getEpochSecond());
            String random = String.valueOf(ThreadLocalRandom.current().nextInt(1000, 9999));
            String signature = getSignature(timestamp, random);
            Map<String, String> parMap = new HashMap<String, String>();
            parMap.put("appkey", this.daigoAppKey);
            parMap.put("appsecret", this.daigoAppSecret);
            parMap.put("t", timestamp);
            parMap.put("r", random);
            parMap.put("s", signature);
            parMap.put("op", "filter");
            parMap.put("action", "cat");

            String result = restTemplateUtil.getData(this.daigoUrl + "?appkey={appkey}&appsecret={appsecret}&t={t}&r={r}&s={s}&op={op}&action={action}", parMap);
             log.info("--------------- daigo获取分类返回结果: {} ---------------", result);

            ObjectMapper mapper = new ObjectMapper();

            daigoCatResResult = mapper.readValue(result, DaigoCateResult.class);

            if(daigoCatResResult != null) {
                daigoCateEntity.addAll(daigoCatResResult.getCateList());
            }

            daigoCateServiceImpl.saveBatch(daigoCateEntity);

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public void getBrandList() throws Exception {
        DaigoBrandResult daigoBrandResult = null;
        try {

            List<DaigoBrand> daigoBrandEntity = new ArrayList<>();
            daigoBrandMapper.deleteAll();

            String timestamp = String.valueOf(Instant.now().getEpochSecond());
            String random = String.valueOf(ThreadLocalRandom.current().nextInt(1000, 9999));
            String signature = getSignature(timestamp, random);
            Map<String, String> parMap = new HashMap<String, String>();
            parMap.put("appkey", this.daigoAppKey);
            parMap.put("appsecret", this.daigoAppSecret);
            parMap.put("t", timestamp);
            parMap.put("r", random);
            parMap.put("s", signature);
            parMap.put("op", "filter");
            parMap.put("action", "brand");

            String result = restTemplateUtil.getData(this.daigoUrl + "?appkey={appkey}&appsecret={appsecret}&t={t}&r={r}&s={s}&op={op}&action={action}", parMap);
            log.info("--------------- daigo获取品牌返回结果: {} ---------------", result);

            ObjectMapper mapper = new ObjectMapper();
            daigoBrandResult = mapper.readValue(result, DaigoBrandResult.class);

            if(daigoBrandResult != null) {
                daigoBrandEntity.addAll(daigoBrandResult.getBrandList());
            }

            daigoBrandServiceImpl.saveBatch(daigoBrandEntity);

        } catch (Exception e) {
            e.printStackTrace();
        }

//        return daigoBrandResult;
    }

}
